package com.lhh.company.website.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhh.company.website.entity.SysException;
import com.lhh.company.website.entity.SysUser;
import com.lhh.company.website.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class SysUserDetailsService implements UserDetailsService {

    /*
     *  UserDetailsService：提供查询用户功能，如根据用户名查询用户，并返回UserDetails
     *UserDetails，SpringSecurity定义的类， 记录用户信息，如用户名、密码、权限等
     * */
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名从数据库中查询用户
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.eq("name",username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(sysUser.getStatus().equals(1)){
            throw new UsernameNotFoundException("账号已封存");
        }
        SysUserDetails sysUserDetails = new SysUserDetails(sysUser);
        return sysUserDetails;
    }
}